import React from 'react';
import { AutoComplete, Card, Image, Upload, Row, Col } from 'antd';
import { Form, Input, Button, Checkbox, Select, message } from 'antd';
import { SyncOutlined } from '@ant-design/icons';

import axios from 'axios';
const { Option } = Select;
const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
    },
};
const tailFormItemLayout = {
    wrapperCol: {
        xs: {
            span: 24,
            offset: 0,
        },
        sm: {
            span: 16,
            offset: 8,
        },
    },
};

export class Register extends React.Component {

    state = {
        codeList: [Math.floor(String(Math.random() * 10)), Math.floor(String(Math.random() * 10)), Math.floor(String(Math.random() * 10)), Math.floor(String(Math.random() * 10))]
    }

    componentDidMount = () => {
        this.generateCode(this.state.code);
    }

    generateCode = () => {
        const codeList = [Math.floor(String(Math.random() * 10)), Math.floor(String(Math.random() * 10)), Math.floor(String(Math.random() * 10)), Math.floor(String(Math.random() * 10))]

        this.setState({
            codeList: codeList
        })



        let c = document.getElementById("code-canvas");
        let ctx = c.getContext("2d");
        // ctx.fillStyle="#ffffff"
        ctx.clearRect(0, 0, 100000, 30000);

        ctx.rotate(-1 * this.lastDegree);
        ctx.font = "20px Arial";



        // this.lastDegree = degree;
        // ctx.rotate(degree * Math.PI / 180);  //-3 to 5

        const colorList = ["red", "darkgreen", "darkblue", "orange"];

        ctx.fillStyle = colorList[Math.floor(Math.random() * 4)];
        ctx.fillText(codeList[0], 20, 20);

        ctx.fillStyle = colorList[Math.floor(Math.random() * 4)];
        ctx.fillText(codeList[1], 40, 20);

        ctx.fillStyle = colorList[Math.floor(Math.random() * 4)];
        ctx.fillText(codeList[2], 60, 20);

        ctx.fillStyle = colorList[Math.floor(Math.random() * 4)];
        ctx.fillText(codeList[3], 80, 20);

        ctx.beginPath(Math.random() * 5, 0);
        ctx.moveTo(Math.random() * 5, 0);
        ctx.lineTo(100, Math.random() * 20 + 10);
        ctx.stroke();


    }


    onFinish = (values) => {
        //delete the unuseful propertise
        delete values.prefix;
        delete values.confirm;
        delete values.agreement;
        //post the information to backend
        axios.post('http://localhost:8080/api/user/register', values)
            .then((response) => {
                if (response.data.success === false) {
                    message.error(response.data.errorMessage);
                } else {
                    message.success('register succeed');
                    //delay 500ms jump to login page after registering succeed
                    setTimeout(() => {
                        window.location.href = "/#/login";
                    }, 500);

                }
            })
            .catch((error) => {
                message.error("Network Error");
                console.log(error);
            });
    };

    onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    }

    render = () => {
        return (

            <div style={{ width: '100vw', display: 'flex', justifyContent: 'center' }}>
                <Card title="Register" extra={<a href="/#/login">Logon</a>} style={{ width: 450, marginTop: 15 }}>
                    <Form
                        {...formItemLayout}
                        name="basic"
                        // labelCol={{ span: 8 }}
                        // wrapperCol={{ span: 16 }}
                        initialValues={{ remember: true }}
                        onFinish={this.onFinish}
                        onFinishFailed={this.onFinishFailed}
                    >
                        <Form.Item
                            label="Username"
                            name="userId"

                            rules={[{ required: true, message: 'Please input your username!' }]}
                        >
                            <Input placeholder="Please input your username" />
                        </Form.Item>

                        <Form.Item
                            label="Password"
                            name="password"
                            rules={[{ required: true, message: 'Please input your password!' }]}
                        >
                            <Input.Password placeholder="Please input your password" />
                        </Form.Item>

                        <Form.Item
                            name="confirm"
                            label="Confirm Password"
                            dependencies={['password']}
                            hasFeedback
                            rules={[
                                {
                                    required: true,
                                    message: 'Please confirm your password!',
                                },
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        if (!value || getFieldValue('password') === value) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error('The two passwords that you entered do not match!'));
                                    },
                                }),
                            ]}
                        >
                            <Input.Password placeholder="Please input your password again" />
                        </Form.Item>

                        <Form.Item
                            label="Address"
                            name="address"
                            rules={[{ required: true, message: 'Please input your Address!' }]}
                        >
                            <Input placeholder="Please input your Address" />
                        </Form.Item>

                        <Form.Item
                            label="Phone"
                            name="mobile"
                            rules={[{ required: true, message: 'Please input your phone number!' }]}
                        >
                            <Input style={{ width: '100%' }} />
                        </Form.Item>

                        <Form.Item
                            label="Gender"
                            name="sex"
                            rules={[{ required: true, message: 'Please select gender!' }]}
                        >
                            <Select placeholder="select your gender">
                                <Option value="male">Male</Option>
                                <Option value="female">Female</Option>
                                <Option value="other">Other</Option>
                            </Select>
                        </Form.Item>

                        <Form.Item
                            label="Email"
                            name="email"
                            rules={[{ required: true, message: 'Please input your Email!' }]}
                        >
                            <Input placeholder="Please input your Email" />
                        </Form.Item>

                        <Form.Item
                            label="Name"
                            name="name"
                            rules={[{ required: true, message: 'Please input your Name!' }]}
                        >
                            <Input placeholder="Please input your Name" />
                        </Form.Item>

                        <Form.Item
                            label="Company"
                            name="company"
                            rules={[{ required: true, message: 'Please input your Company!' }]}
                        >
                            <Input placeholder="Please input your Company" />
                        </Form.Item>

                        <Form.Item label="Captcha" extra="We must make sure that your are a human.">
                            <Row gutter={8}>
                                <Col span={10}>
                                    <Form.Item
                                        name="code"
                                        noStyle
                                        rules={[{ required: true, message: 'Please input the captcha you got!' },
                                        () => ({
                                            validator: (_, value) => {
                                                console.log(value)
                                                if (value && value === this.state.codeList.join("")) {
                                                    return Promise.resolve();
                                                }
                                                return Promise.reject(new Error('The error code!'));
                                            },
                                        }),
                                        ]}
                                    >
                                        <Input />
                                    </Form.Item>
                                </Col>
                                <Col span={10}>
                                    <canvas id="code-canvas" width="100" height="30" style={{ border: "1px solid #d3d3d3" }}>
                                        Not supported</canvas>
                                </Col>
                                <Col span={4}>
                                    <Button type="text" icon={<SyncOutlined />} onClick={
                                        () => {

                                            this.generateCode();
                                        }
                                    }></Button>
                                </Col>

                            </Row>
                        </Form.Item>

                        <Form.Item
                            name="agreement"
                            valuePropName="checked"
                            rules={[
                                {
                                    validator: (_, value) =>
                                        value ? Promise.resolve() : Promise.reject(new Error('Should accept agreement')),
                                },
                            ]}
                            {...tailFormItemLayout}
                        >
                            <Checkbox>
                                I have read the <a href="" target="_blank">agreement</a>
                            </Checkbox>
                        </Form.Item>
                        <Form.Item {...tailFormItemLayout}>
                            <Button type="primary" htmlType="submit">
                                Register
                            </Button>
                        </Form.Item>

                    </Form>
                </Card>
            </div>

        )
    }
}